#include<stdio.h>
#include<stdlib.h>
#include<string.h>


#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define ElemType int

typedef struct DuLNode {
    int data;
    struct DuLNode *prior;
    struct DuLNode *next;
} DuLNode, *DuLinkList;

DuLinkList CreateList_DuL()
//随机产生n个元素的值，建立带头结点的双链线性表L
{
    DuLinkList L = (DuLinkList) malloc(sizeof(DuLNode));//创建头结点
    if (L == NULL) {
        printf("内存分配失败\n");
        return NULL;
    }
    L->prior = L;
    L->next = L;
    return L;
}

DuLinkList GetEle_DulL(DuLinkList L, int i)
//返回双链线性表L中第i个位置的元素结点指针
{
    if(L == NULL || i < 1) {
        return NULL;
    }  
    DuLinkList p = L->next;
    int j = 1;
    while(p != L && j < i) {
        p = p->next;
        j++;
    }
    return p;
}

int ListInsert_DuL(DuLinkList *L, int i, ElemType e)
//在双链线性表L中第i个位置之前插入新的元素e
{
    DuLinkList p = GetEle_DulL(*L,i);
    
    if(p == NULL) {
        return ERROR;
    }//第i个元素不存在

    DuLinkList s = (DuLinkList) malloc(sizeof(DuLNode));
    if(!s) {
        return ERROR;
    }//存储分配失败
    s->data = e;
    s->next = p;
    s->prior = p->prior;

    if(p->prior != NULL) {
        p->prior->next = s;
    }
    p->prior = s;
    return OK;
}

int main()
{
    // 这里可以测试你的双链表功能
    DuLinkList L = CreateList_DuL();
    ListInsert_DuL(&L, 1, 10);
    ListInsert_DuL(&L, 2, 20);
    ListInsert_DuL(&L, 3, 30);
    ListInsert_DuL(&L, 1, 0);
    DuLinkList p = L->next;
    while(p != L) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
    return 0;
}